
export class OnlineManager {
    static Current: OnlineManager = new OnlineManager();
    private timer;
    private isTimerOn: boolean;
    private fnObj: TimerAction = <any>{};
    /**
     * 启动定时器
     */
    private startTimer(interval: number) {
        if (!this.isTimerOn) {
            this.isTimerOn = true;
            this.action(interval);
        }
    }
    /**
     * 关闭定时器
     */
    stopTimer() {
        clearInterval(this.timer);
        this.isTimerOn = false;
    }
    /**
     * 添加定时任务
     */
    add(action: () => Promise<any>, successCB?: Function, errCB?: Function) {
        this.fnObj.action = action;
        this.fnObj.successCB = successCB;
        this.fnObj.errCB = errCB;
        this.run();
    }
    /**
     * 运行传入的方法
     */
    run() {
        this.stopTimer();
        this.fnObj.action().then(() => {
            this.fnObj.successCB();
            this.startTimer(10000);
        }).catch(() => {
            this.fnObj.errCB();
            this.startTimer(10000);
        });
    }
    /**
     * 讲方法放入定时器
     */
    private action(interval: number) {
        this.timer = setInterval(this.run.bind(this), interval)
    }
}

export interface TimerAction {
    action: () => Promise<any>;
    successCB: Function;
    errCB: Function;
}